package com.hms.dao.impl;

// Generated Oct 7, 2013 3:06:28 PM by Hibernate Tools 3.4.0.CR1

import static org.hibernate.criterion.Example.create;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinType;

import com.hibernate.beans.Ptnt;
import com.hms.dao.PatientDAO;
import com.hms.vo.beans.PatientQueryCriteriaVO;

/**
 * Home object for domain model class Ptnt.
 * @see com.hibernate.beans.Ptnt
 * @author Hibernate Tools
 */
public class PatientDAOImpl implements PatientDAO {

	private static final Log log = LogFactory.getLog(PatientDAOImpl.class);

	private SessionFactory sessionFactory;

	/*protected SessionFactory getSessionFactory() {
		try {
			return (SessionFactory) new InitialContext()
					.lookup("SessionFactory");
		} catch (Exception e) {
			log.error("Could not locate SessionFactory in JNDI", e);
			throw new IllegalStateException(
					"Could not locate SessionFactory in JNDI");
		}
	}*/

	/* (non-Javadoc)
	 * @see com.hms.dao.impl.PatientDAO#getSessionFactory()
	 */
	public SessionFactory getSessionFactory() {
		System.out.println("PatientDAOImpl.java:Getting Session Factory" + sessionFactory);
		return sessionFactory;
	}
	
	/* (non-Javadoc)
	 * @see com.hms.dao.impl.PatientDAO#setSessionFactory(org.hibernate.SessionFactory)
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		System.out.println("PatientDAOImpl.java:Setting Session Factory to " + sessionFactory);
		this.sessionFactory = sessionFactory;
	}



	/* (non-Javadoc)
	 * @see com.hms.dao.impl.PatientDAO#persist(com.hms.dao.impl.PatientDAO)
	 */
	public void persist(Ptnt transientInstance) {
		log.debug("persisting Ptnt instance");
		try {
			sessionFactory.getCurrentSession().persist(transientInstance);
			log.debug("persist successful");
		} catch (RuntimeException re) {
			log.error("persist failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.hms.dao.impl.PatientDAO#attachDirty(com.hms.dao.impl.PatientDAO)
	 */
	public void attachDirty(Ptnt instance) {
		log.debug("attaching dirty Ptnt instance");
		try {
			sessionFactory.getCurrentSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.hms.dao.impl.PatientDAO#attachClean(com.hms.dao.impl.PatientDAO)
	 */
	public void attachClean(Ptnt instance) {
		log.debug("attaching clean Ptnt instance");
		try {
			sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.hms.dao.impl.PatientDAO#delete(com.hms.dao.impl.PatientDAO)
	 */
	public void delete(Ptnt persistentInstance) {
		log.debug("deleting Ptnt instance");
		try {
			sessionFactory.getCurrentSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.hms.dao.impl.PatientDAO#merge(com.hms.dao.impl.PatientDAO)
	 */
	public Ptnt merge(Ptnt detachedInstance) {
		log.debug("merging Ptnt instance");
		try {
			Ptnt result = (Ptnt) sessionFactory.getCurrentSession().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.hms.dao.impl.PatientDAO#findById(java.lang.Integer)
	 */
	public Ptnt findById(java.lang.Integer id) {
		log.debug("getting Ptnt instance with id: " + id);
		try {
			Ptnt instance = (Ptnt) sessionFactory.getCurrentSession().get(
					"com.hibernate.beans.Ptnt", id);
			if (instance == null) {
				log.debug("get successful, no instance found");
			} else {
				log.debug("get successful, instance found");
			}
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.hms.dao.impl.PatientDAO#findByExample(com.hms.dao.impl.PatientDAO)
	 */
	public List<Ptnt> findByExample(PatientDAO instance) {
		log.debug("finding Ptnt instance by example");
		try {
			List<Ptnt> results = (List<Ptnt>) sessionFactory
					.getCurrentSession()
					.createCriteria("com.hibernate.beans.Ptnt")
					.add(create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List<Ptnt> searchPatient(PatientQueryCriteriaVO ptntQueryCriteriaVO) {
		try {
			Session session = getSession();
			
			Criteria patientQuery = session.createCriteria("com.hibernate.beans.Ptnt");
			Criteria patientQueryWithCriteria = addCriteriaToPatientQuery(ptntQueryCriteriaVO,patientQuery);
			
			@SuppressWarnings("unchecked")
			List<Ptnt> results = (List<Ptnt>) patientQueryWithCriteria.list();
						
			log.debug("find by example successful, result size: " + results.size());
			log.debug("Result: " + results);
			
			return results;

		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}
	
	public static Criteria addCriteriaToPatientQuery(
			PatientQueryCriteriaVO ptntQueryCriteriaVO, Criteria patientQueryCriteria) {
		
		if(ptntQueryCriteriaVO!=null)
		{
			String firstName = ptntQueryCriteriaVO.getPatientFirstName();
			if(firstName != null && !"".equals(firstName))
			{
				firstName = firstName.trim();
				Criterion firstNamefilterCriterion = Restrictions.ilike(Ptnt.MemberVariables.PTNT_FST_NM.getMemberVariableName(),
						firstName,MatchMode.ANYWHERE);
				patientQueryCriteria.add(firstNamefilterCriterion);
			}
			
			String lastName = ptntQueryCriteriaVO.getPatientLastName();
			if(lastName != null && !"".equals(lastName))
			{
				lastName = lastName.trim();
				Criterion lastNamefilterCriterion = Restrictions.ilike(Ptnt.MemberVariables.PTNT_LST_NM.getMemberVariableName(),
						lastName,MatchMode.ANYWHERE);
				patientQueryCriteria.add(lastNamefilterCriterion);
			}
			
			String contactNumber = ptntQueryCriteriaVO.getPatientContactNumber();
			if(contactNumber != null && !"".equals(contactNumber))
			{
				contactNumber = contactNumber.trim();
				patientQueryCriteria = patientQueryCriteria.createAlias(Ptnt.MemberVariables.PTNT_CNTCTS.getMemberVariableName(), 
						"patientContactNumbers", JoinType.INNER_JOIN);
				
				Criterion contactNumberCriterion = Restrictions.ilike("patientContactNumbers.ptntCntctNbr", contactNumber, MatchMode.ANYWHERE);
				patientQueryCriteria.add(contactNumberCriterion);
			}
		}
		return patientQueryCriteria;
	}
	
	private Session getSession()
	{
		Session session = getSessionFactory().openSession();
		
		System.out.println("PatientDAOImpl.java - session = " + session);
		
		if(session == null)
		{
			session = getSessionFactory().openSession();
		}		
		
		return session;
	}
}
